<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="配置名称" prop="s_name">
          <el-input v-model="queryParams.s_name" placeholder="输入配置名称" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="s_code">
          <el-input v-model="queryParams.s_code" placeholder="输入code" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/common/setting/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button :disabled="selectIds.length === 0" v-hasPerm="'/admin/common/setting/del'" type="danger"
            icon="delete" @click="handleDelete()">
            删除
          </el-button>
        </div>
        <div>
          <el-button v-hasPerm="['/admin/common/setting/refreshAll']" type="primary" icon="refresh"
            @click="handleRefresh()">
            刷新
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="id" prop="id" width="100" />
        <el-table-column label="唯一标识" prop="code" width="200" />
        <el-table-column label="配置名称" prop="name" min-width="150" />
        <el-table-column label="选中值" align="center" prop="val" width="300">
          <template #default="scope">
            <template v-if="scope.row.input_type == 'text' || scope.row.input_type == 'textarea'">
              <div>{{ scope.row.val }}</div>
            </template>
            <template v-else-if="scope.row.input_type == 'editor'">
              <!-- v-html="scope.row.val" -->
              <div></div>
            </template>
            <template v-else-if="scope.row.input_type == 'radio'">
              <div v-for="(item) in scope.row.ext" :key="item.id">
                <div v-if="item.id == scope.row.val">{{ item.name }}</div>
              </div>
            </template>
            <template v-else-if="scope.row.input_type == 'checkbox'">
              <template v-for="(item) in scope.row.ext" :key="item.id">
                <template v-for="v in scope.row.val.split(',')" :ket="v">
                  <span v-if="item.id == v">{{ item.name }}、</span>
                </template>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="200" />
        <el-table-column align="center" fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button v-hasPerm="'/admin/common/setting/update'" type="primary" icon="edit" link size="small"
              @click="handleOpenDialog(scope.row.id, scope.row)">
              编辑
            </el-button>
            <el-button v-hasPerm="'/admin/common/setting/del'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 表单 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" :title="dialog.title" destroy-on-close
      append-to-body width="60%" @close="closeDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="code">
          <el-input v-model="formData.code" placeholder="请输入唯一标识" :disabled="isEdit" />
        </el-form-item>

        <el-form-item label="类型" prop="input_type">
          <el-radio-group v-model="formData.input_type" @change="hanldeChangeRadio" :disabled="isEdit">
            <el-radio value="text">输入框</el-radio>
            <el-radio value="radio">单选</el-radio>
            <el-radio value="checkbox">多选</el-radio>
            <el-radio value="editor">富文本</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.input_type == 'checkbox' || formData.input_type == 'radio'">
          <el-form-item :label="String.fromCharCode(64 + (index + 1))" v-for="(item, index) in formData.extJson"
            :key="item.id">
            <div class="flex" style="width: 100%;">
              <el-input clearable class="mr-10 flex-1" v-model="item.name" placeholder="请输入选项" />
              <div style="width: 100px;">
                <el-button @click="hanldeDelChoice(index)" v-if="index > 1" type="danger">删除选项</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-button type="primary" @click="addChoiceList">新增选项</el-button>
              <span>（最多添加10个选项）</span>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="选中值" prop="val">
          <el-checkbox-group v-if="formData.input_type == 'checkbox'" v-model="formData.checkbox" size="small">
            <el-checkbox v-for="(item) in formData.extJson" :value="item.id" border :label="item.name" :key="item.id" />
          </el-checkbox-group>

          <el-radio-group v-else-if="formData.input_type == 'radio'" v-model="formData.val">
            <el-radio v-for="(item) in formData.extJson" :value="item.id" :key="item.id">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
          <el-input v-else-if="formData.input_type == 'text'" v-model="formData.val" placeholder="请输入选中值" />
          <div v-else-if="formData.input_type == 'editor'" style="height: 400px; border: 1px solid #EBEEFF;">
            <editor v-model="formData.val" style="height:300px; width: 100%;" />
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MyNotice",
  inheritAttrs: false,
});

import SetAPI, { PageVO, SetPageQuery, configForm } from "@/api/system/setting";
import Editor from "@/components/WangEditor/index.vue";
const queryFormRef = ref(ElForm);
const pageData = ref<PageVO[]>([]);
const loading = ref(false);
const total = ref(0);
const queryParams = reactive<SetPageQuery>({
  page: 1,
  ps: 10,
});

const formRef = ref(ElForm);

// 选中的ID
const selectIds = ref<number[]>([]);


// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 正则验证
const rules = reactive({
  code: [{ required: true, message: "请输入唯一标识", trigger: "blur" }],
  name: [{ required: true, message: "请输入标题", trigger: "blur" }],
  val: [{ required: true, message: "请输入内容", trigger: "blur" }],
});
const dialog = reactive({
  visible: false,
  title: "新增公告",
});

const formData = reactive<configForm>({
  id: '',
  code: '',
  name: '',
  input_type: 'text',
  val: '',
  ext: '',
  pid: 0,
  sort: 0,
  remark: '',
  checkbox: [],
  extJson: ''
});


// 点击刷新数据
const handleRefresh = () => {
  SetAPI.refreshAll().then(res => {
    ElMessage.success("刷新成功");
    closeDialog();
  })
}

// 新增选项
const addChoiceList = () => {
  if (formData.extJson.length >= 10) {
    ElMessage.warning('选项不能超过10个');
    return;
  }
  formData.extJson.push({ name: '', id: formData.extJson.length + 1 + '' });
}

// 删除选项
const hanldeDelChoice = (index: number) => {
  formData.extJson.splice(index, 1);
}


// 默认值
const hanldeChangeRadio = (val: any) => {
  if (formData.input_type == 'text') {
    formData.extJson = '';
  } else if (formData.input_type == 'radio') {
    formData.extJson = [{ name: '', id: '1' }, { name: '', id: '2' }]
  } else if (formData.input_type == 'checkbox') {
    formData.extJson = [{ name: '', id: '1' }, { name: '', id: '2' }]
  }
}

// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.input_type == 'radio') {
        formData.val = formData.val + '';
      } else if (formData.input_type == 'checkbox') {
        formData.val = formData.checkbox.join(',');
      }
      if (formData.id) {
        SetAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        formData.ext = JSON.stringify(formData.extJson);
        SetAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  handleResetQuery();
}

/**
 * 打开弹窗
 *
 * @param id 公告ID
 */

// 新增或者修改
const isEdit = ref(false);

async function handleOpenDialog(postId?: number | string, data?: any) {
  dialog.visible = true;
  if (postId) {

    console.log(data);
    Object.assign(formData, data);
    formData.extJson = formData.ext;
    if (formData.input_type == 'checkbox') {
      formData.checkbox = formData.val.split(',');
    }
    isEdit.value = true;
    dialog.title = "修改设置";
  } else {
    isEdit.value = false;
    dialog.title = "新增设置";
  }
}


/**
 * 删除用户
 *
 * @param id  ID
 */
function handleDelete(id?: number) {
  let userIds = id ? [id] : selectIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      SetAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  SetAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();


  formData.id = '';
  formData.code = '';
  formData.name = '';
  formData.sort = 0;
  formData.input_type = 'text';
  formData.val = '';
  formData.ext = [];
  formData.extJson = [];
  formData.pid = 0;
  formData.remark = '';
}

onMounted(() => {
  handleQuery();
});
</script>
